package com.lq.util;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Aspect
@Component
public class AopUtil {
    private static Logger logger= LoggerFactory.getLogger(AopUtil.class);

    @Pointcut(value = "execution (public * com.lq.controller.*.*(..))")
    public void log(){

    }

    @Before(value = "log()")
    public void doBefore(JoinPoint joinPoint){
        //接收到请求，记录请求内容
        ServletRequestAttributes attributes= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request=attributes.getRequest();
        //记录以下请求内容
        System.out.println("URL:"+request.getRequestURL().toString());
        System.out.println("HttpMethod:"+request.getMethod());
        System.out.println("IP:"+request.getRemoteAddr());
        System.out.println("Port:"+request.getRemotePort());
        System.out.println("方法全路径:"+ joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        System.out.println("方法参数:"+ Arrays.toString(joinPoint.getArgs()));
        logger.info("Aop前置拦截");
    }

    @AfterReturning(returning = "ret", pointcut = "log()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求，返回内容
        System.out.println("方法的返回值 : " + ret);
    }

    //后置最终通知,final增强，不管是抛出异常或者正常退出都会执行
     @After(value = "log()")
     public void doAfter() {
         logger.info("AOP 后置方法已经成功执行完毕");
     }

}
